package cn.wangzg.course0902;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.wangzg.course0902.adapter.CommonAdapter;
import cn.wangzg.course0902.adapter.ViewHolder;
import cn.wangzg.course0902.service.PlayService;
import cn.wangzg.course0902.util.MusicUtil;

public class MainActivity extends BaseActivity {
    private ContentResolver resolver;
    private CommonAdapter<Music> adapter;
    private ArrayList<Music> musics;

    //屏幕下方播放控制的五个组件
    private ImageView iv_play;
    private ImageView iv_next;
    private ImageView iv_music;
    private TextView tv_title;
    private TextView tv_artist;
    private ProgressBar pb_music;
    private SwipeRefreshLayout swl_list;

    private Intent service;
    private PlayService playService;
    MyApp app;
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PlayService.PlayBinder playBinder = (PlayService.PlayBinder) service;
            playService=playBinder.getPlayService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            playService=null;
        }
    };
    //定时器
    Timer timer;
    TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        resolver=getContentResolver();
        app= (MyApp) getApplication();

        service=new Intent(this, PlayService.class);
        startService(service);
        bindService(service,conn,BIND_AUTO_CREATE);
        initView();
        getMusic();

    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mainmenu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.m_refresh:
                //Toast.makeText(this, "click", Toast.LENGTH_SHORT).show();
                refreshMusic();
                break;
        }
        return true;
    }

    private void getMusic() {
        requestRunPermisssion(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                new PermissionListener() {
            @Override
            public void onGranted() {
                musics=MusicUtil.getMusic(resolver);
                adapter.setmDatas(musics);
                //设置组件的刷洗状态；false代表关闭
                swl_list.setRefreshing(false);
            }

            @Override
            public void onDenied(List<String> deniedPermission) {

            }
        });
    }
    private void refreshMusic() {
        requestRunPermisssion(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                new PermissionListener() {
            @Override
            public void onGranted() {
                MusicUtil.mediaScan(MainActivity.this, Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DOWNLOADS));
            }

            @Override
            public void onDenied(List<String> deniedPermission) {

            }
        });
    }

    private void initView() {
        iv_next=findViewById(R.id.iv_next);
        iv_play=findViewById(R.id.iv_play);
        iv_music=findViewById(R.id.iv_music);
        tv_title=findViewById(R.id.tv_name);
        tv_artist=findViewById(R.id.tv_artist);
        pb_music=findViewById(R.id.pb_music);
        iv_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //playService.next();
                service.putExtra("action",4);
                startService(service);
            }
        });
        iv_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playService.isPlaying()) {//正在播放，则暂停
                    //playService.pause();
                    service.putExtra("action",2);
                    startService(service);
                }else {//暂停，则继续播放
                    //playService.start();
                    service.putExtra("action",3);
                    startService(service);
                }
            }
        });

        swl_list=findViewById(R.id.swl_list);
        //设置进度圈的大小;(这里面只有两个值SwipeRefreshLayout.LARGE和DEFAULT，后者是默认效果)
        swl_list.setSize(SwipeRefreshLayout.LARGE);
        //设置进度圈的背景色。这里随便给他设置了一个颜色：浅绿色
        swl_list.setProgressBackgroundColorSchemeColor(Color.CYAN);
        //设置进度动画的颜色。这里面最多可以指定四个颜色，我这也是随机设置的，大家知道怎么用就可以了
        swl_list.setColorSchemeResources(android.R.color.holo_orange_dark
                ,android.R.color.holo_blue_dark
                ,android.R.color.holo_red_dark
                ,android.R.color.widget_edittext_dark);
        //设置手势滑动监听器
        swl_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public void onRefresh() {
                getMusic();
            }
        });

        ListView lvMusic=findViewById(R.id.listMusic);
        adapter=new CommonAdapter<Music>(this,musics,R.layout.music_item) {
            @Override
            public void convert(ViewHolder helper, Music item) {
                helper.setText(R.id.tv_name,item.getTitle());
                helper.setText(R.id.tv_artist,item.getArtist_name());
                helper.setText(R.id.tv_duration,MusicUtil.timeFormat(item.getFile_duration()));
                Bitmap bm = MusicUtil.getAlbumArt(resolver, item.getAlbum_id());
                if(bm!=null) {
                    helper.setImageBitmap(R.id.iv_music,bm);
                }
            }
        };
        lvMusic.setAdapter(adapter);
        //点击歌曲，则开始播放该歌曲
        lvMusic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //如何把歌曲列表送到服务中去
                playService.setMusics(musics);
                app.musics=musics;

                playService.play(position);
                //service.putExtra("action",1);
                //service.putExtra("pos",position);
                //startService(service);
                //执行的任务
                task=new TimerTask() {
                    @Override
                    public void run() {
                        //从服务获取歌曲播放进度，歌曲在列表的位置，是否正在播放
                        //根据以上信息，设置Activity下部的歌曲播放的状态
                        int curPos = playService.getCurPos();
                        final Music music=musics.get(curPos);
                        //pb_music.setMin(0);
                        pb_music.setMax(music.getFile_duration());
                        int currentProgress = playService.getCurrentProgress()/1000;
                        pb_music.setProgress(currentProgress);
                        //如果要操作组件（Widget，控件，视图view），需要切换到主线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_title.setText(music.getTitle());
                                tv_artist.setText(music.getArtist_name());
                                iv_play.setSelected(playService.isPlaying());
                            }
                        });
                    }
                };
                timer=new Timer();
                //启动定时任务   1 执行的任务；2 延迟的时间 3 执行任务的间隔
                timer.schedule(task,0,1000);
                //会使用广播的方式来实现
            }
        });
    }

}
